package com.sk.cardeal.act.home.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.ApplyAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.ApplyBean;
import com.sk.cardeal.entity.ApplyDetails;
import com.sk.cardeal.entity.ApplyListBean;
import com.sk.cardeal.entity.SaveApplyBean;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.MultiStateView;
import com.sk.cardeal.view.SimpleMultiStateView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/12/22.
 */

public class ChooseApplyActivity extends BaseActivity implements HandleDataCallBack, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.apply_form)
    TextView applyForm;
    @BindView(R.id.SimpleMultiStateView)
    SimpleMultiStateView simpleMultiStateView;

    private int type;
    private int page = 0;

    private LoadingDialog loadingDialog;

    private List<ApplyBean> allDataList = new ArrayList<>();
    private List<ApplyDetails> applyList = new ArrayList<>();

    private ApplyAdapter adapter;
    private boolean isLoadMore = false;
    private SaveApplyBean saveApplyBean;

    @Override
    protected int getContentView() {
        return R.layout.activity_choose_apply;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initStateView();

        saveApplyBean = new SaveApplyBean();
        saveApplyBean.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
        saveApplyBean.setUserId(MyUtils.getUser(mContext).getId());
        saveApplyBean.setCode(MyUtils.getRndNumCode());
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        type = getIntent().getIntExtra("type", 0);
        switch (type) {
            case 0:
                tvTitle.setText("选择配件");
                saveApplyBean.setType(0);
                break;
            case 1:
                tvTitle.setText("选择机具");
                saveApplyBean.setType(1);
                break;
            case 2:
                tvTitle.setText("选择耗材");
                saveApplyBean.setType(2);
                break;
        }
        dataRyc.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new ApplyAdapter(R.layout.item_apply, allDataList);
        dataRyc.setAdapter(adapter);

        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_view, null);
        TextView textView = emptyView.findViewById(R.id.content);
        textView.setText("暂无可选的产品哦!");
        adapter.setEmptyView(emptyView);

        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, dataRyc);
        AppApi.getApplyPartInfo(type, page, this, 0, this);
    }

    @OnClick({R.id.back, R.id.apply_form})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.apply_form:
                if (applyList.size() > 0) {
                    loadingDialog.show();
                    saveApplyBean.setDetailList(applyList);
                    AppApi.saveApply(saveApplyBean, ChooseApplyActivity.this, 1, ChooseApplyActivity.this);
                } else {
                    SnackUtils.showError(mRootView, "您尚未选择任何商品！");
                }
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                ApplyListBean applyListBean = JSON.parseObject(result, ApplyListBean.class);
                List<ApplyBean> applyBeanList = applyListBean.getResultList();
                showSuccess();
                allDataList.addAll(applyBeanList);
                if (allDataList.size() < 10) {
                    adapter.setEnableLoadMore(false);
                } else {
                    adapter.setEnableLoadMore(true);
                }
                if (isLoadMore) {
                    adapter.loadMoreComplete();
                    if (allDataList.size() == 0) {
                        adapter.loadMoreEnd();
                    }
                    isLoadMore = false;
                }
                adapter.notifyDataSetChanged();
                break;
            case 1:
                setResult(RESULT_OK);
                Toast.makeText(mContext, "申领单保存成功！", Toast.LENGTH_SHORT).show();
                finish();
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.add:
                int stock = allDataList.get(position).getStockNum();
                int num = allDataList.get(position).getCount();
                if (num < stock) {
                    num++;
                    allDataList.get(position).setCount(num);
                    addSelect(allDataList.get(position));
                    adapter.notifyItemChanged(position);
                } else {
                    SnackUtils.showError(mRootView, "库存不足！");
                }
                break;
            case R.id.reduce:
                int num1 = allDataList.get(position).getCount();
                if (num1 > 0) {
                    num1--;
                    allDataList.get(position).setCount(num1);
                    reduceSelect(allDataList.get(position));
                    adapter.notifyItemChanged(position);
                }
                break;
        }
    }

    private void addSelect(ApplyBean applyBean) {

        ApplyDetails applyDetails = new ApplyDetails();
        applyDetails.setCount(String.valueOf("1"));
        applyDetails.setName(applyBean.getName());
        applyDetails.setPartId(applyBean.getId());
        applyDetails.setStockNum(String.valueOf(applyBean.getStockNum()));

        if (applyList.size() == 0) {
            applyList.add(applyDetails);
        } else {
            boolean isSelect = false;
            for (int i = 0; i < applyList.size(); i++) {
                ApplyDetails bean = applyList.get(i);
                if (applyBean.getId().equals(bean.getPartId())) {
                    isSelect = true;
                    int count = Integer.parseInt(bean.getCount());
                    count++;
                    bean.setCount(String.valueOf(count));
                    break;
                }
            }
            if (!isSelect) {
                applyList.add(applyDetails);
            }
        }
        tvTip.setText("已选择" + caculateTotal() + "件商品");
    }

    private void reduceSelect(ApplyBean applyBean) {

        ApplyDetails applyDetails = new ApplyDetails();
        applyDetails.setCount(String.valueOf("1"));
        applyDetails.setName(applyBean.getName());
        applyDetails.setPartId(applyBean.getId());
        applyDetails.setStockNum(String.valueOf(applyBean.getStockNum()));

        if (applyList.size() == 0) {
            Toast.makeText(mContext, "您未选中任何商品！", Toast.LENGTH_SHORT).show();
        } else {
            for (int i = 0; i < applyList.size(); i++) {
                ApplyDetails bean = applyList.get(i);
                if (applyBean.getId().equals(bean.getPartId())) {
                    int count = Integer.parseInt(bean.getCount());
                    count--;
                    bean.setCount(String.valueOf(count));
                    if (count == 0) {
                        applyList.remove(i);
                    }
                    break;
                }
            }
        }
        tvTip.setText("已选择" + caculateTotal() + "件商品");
    }

    private int caculateTotal() {
        int total = 0;
        for (ApplyDetails applyDetails : applyList) {
            total += Integer.parseInt(applyDetails.getCount());
        }
        return total;
    }


    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        AppApi.getApplyPartInfo(type, page, this, 0, this);
    }

    private void initStateView() {
        if (simpleMultiStateView == null) return;
        simpleMultiStateView.setEmptyResource(R.layout.view_empty)
                .setRetryResource(R.layout.view_retry)
                .setLoadingResource(R.layout.view_loading)
                .setNoNetResource(R.layout.view_nonet)
                .build()
                .setonReLoadlistener(new MultiStateView.onReLoadlistener() {
                    @Override
                    public void onReload() {
                    }
                });
    }

    public void showLoading() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showLoadingView();
        }
    }

    public void showSuccess() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showContent();
        }
    }

    public void showFaild() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showErrorView();
        }
    }

    public void showNoNet() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showNoNetView();
        }
    }
}
